//
//  FoThreeViewController.m
//  Everest
//
//  Created by Liu Chengbo on 14/12/27.
//  Copyright (c) 2014年 ThreeL. All rights reserved.
//

#import "FoThreeViewController.h"
#import "NetHandler.h"
#import "FocusThree.h"
#import "UIImageView+WebCache.h"
#import "FoThreeCell.h"
#import "FocusThreeAlbumCell.h"
#import "FocusFetail.h"
#import "UIColor+AddColor.h"
#import "TwoType.h"
#import "PlayViewController.h"
#import "AlbumViewController.h"
#import "Album.h"
#import "ClassifyDetail.h"
#import "AlbumTracks.h"
#import "FilesDownManage.h"
#import "NetHandleData.h"
#import "JingRoundView.h"
#import "AppDelegate.h"
#import "WeiboSDK.h"
#import "AvReadioPlayer.h"

#define REDIRECTURI @"http://www.sharesdk.cn"
#define kWidth [UIApplication sharedApplication].keyWindow.bounds.size.width

@interface FoThreeViewController () <UITableViewDataSource, UITableViewDelegate, JingRoundViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIImageView *bigImageView;
@property (nonatomic, retain) UILabel *titleLabel;
@property (nonatomic, retain) UILabel *contLabel;
@property (nonatomic, retain) UILabel *autherLabel;
@property (nonatomic, retain) UIImageView *smallImageView;
@property (nonatomic, retain) UILabel *nameLabel;
@property (nonatomic, retain) UIButton *favourButton;
@property (nonatomic, retain) UIButton *talkButton;
@property (nonatomic, retain) UIButton *downLoadButton;
@property (nonatomic, retain) UIView *backView;
@property (nonatomic, retain) JingRoundView *roundView;
@property (nonatomic, assign) BOOL click;

@property (nonatomic, retain) FocusThree *foc;
@property (nonatomic, retain) NSMutableArray *arr;
@property (nonatomic, retain) NSMutableArray *typeOneArr;
@property (nonatomic, retain) NSMutableArray *typeTwoArr;
@property (nonatomic, retain) NSNumber *number;
@end

@implementation FoThreeViewController
- (void)dealloc
{
    [_roundView release];
    [_backView release];
    [_number release];
    [_typeOneArr release];
    [_typeTwoArr release];
    [_focus release];
    [_foc release];
    [_arr release];
    [_tableView release];
    [_bigImageView release];
    [_contLabel release];
    [_autherLabel release];
    [_smallImageView release];
    [_nameLabel release];
    [_favourButton release];
    [_talkButton release];
    [_downLoadButton release];
    [super dealloc];
}
- (void)handleData
{
    // 请求1
    NSString *str = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/subject_detail?id=%@&device=iPhone", self.focus.specialId];
    NSLog(@"=====%@", str);
    [NetHandleData getDataWithUrl:str completion:^(NSData *data) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        
        NSDictionary *dic = [result objectForKey:@"info"];
        
        self.foc = [[FocusThree alloc] initWithDictionary:dic];
        
        self.number = [dic objectForKey:@"contentType"];
        NSLog(@"%@", self.number);
        
        // 创建大照片
        self.bigImageView = [[UIImageView alloc] init];
        [self.bigImageView setImageWithURL:[NSURL URLWithString:self.foc.coverPathBig]];
        self.bigImageView.frame = CGRectMake(0, 0, self.view.bounds.size.width, 150);
        
        // 创建标题
        self.titleLabel = [[UILabel alloc] init];
        self.titleLabel.frame = CGRectMake(0, 150, self.view.bounds.size.width, 50);
        self.titleLabel.textColor = [UIColor sectionColor];
        self.titleLabel.font = [UIFont systemFontOfSize:16];
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        
        // 创建内容
        NSString *cont = self.foc.intro;
        NSDictionary *dic1 = @{NSFontAttributeName:[UIFont systemFontOfSize:13]};
        CGRect rect = [cont boundingRectWithSize:CGSizeMake(self.view.bounds.size.width - 20, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic1 context:nil];
        self.contLabel = [[UILabel alloc] init];
        self.contLabel.frame = CGRectMake(10, 200, self.view.bounds.size.width - 20, rect.size.height);
        self.contLabel.text = cont;
        self.contLabel.textColor = [UIColor grayColor];
        self.contLabel.font = [UIFont systemFontOfSize:13];
        self.contLabel.numberOfLines = 0;
        [self.contLabel sizeToFit];
        
        // 创建"小编"
        self.autherLabel = [[UILabel alloc] init];
        self.autherLabel.frame = CGRectMake(10, 210 + self.contLabel.frame.size.height, 30, 20);
        self.autherLabel.text = @"小编";
        self.autherLabel.textColor = [UIColor grayColor];
        self.autherLabel.font = [UIFont systemFontOfSize:13];
        
        // 创建小照片
        self.smallImageView = [[UIImageView alloc] init];
        self.smallImageView.frame = CGRectMake(self.autherLabel.frame.origin.x + 30 + 5, self.autherLabel.frame.origin.y, 20, 20);
        
        // 创建编者名字
        self.nameLabel = [[UILabel alloc] init];
        self.nameLabel.frame = CGRectMake(self.smallImageView.frame.origin.x + 20 + 5, self.autherLabel.frame.origin.y, kWidth - 30 - 20 - 10 , 20);
        self.nameLabel.textColor = [UIColor grayColor];
        self.nameLabel.textAlignment = NSTextAlignmentLeft;
        self.nameLabel.font = [UIFont systemFontOfSize:14];
        
        // 添加到tableViewheader上
        UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 240 + self.contLabel.frame.size.height)];
        headView.backgroundColor = [UIColor whiteColor];
        [headView addSubview:self.bigImageView];
        [headView addSubview:self.titleLabel];
        [headView addSubview:self.contLabel];
        [headView addSubview:self.autherLabel];
        [headView addSubview:self.smallImageView];
        [headView addSubview:self.nameLabel];
        self.tableView.tableHeaderView = headView;
        
        // 赋值
        [self.bigImageView setImageWithURL:[NSURL URLWithString:self.focus.coverPathBig]];
        [self.smallImageView setImageWithURL:[NSURL URLWithString:self.foc.smallLogo]];
        self.titleLabel.text = self.foc.title;
        self.contLabel.text = self.foc.intro;
        self.nameLabel.text = self.foc.nickname;
        
//        [self.tableView reloadData];
    }];
    
    // 请求 http://mobile.ximalaya.com/m/subject_detail
    
    
    // 请求2
    NSString *str1 = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/subject_detail?id=%@&device=iPhone", self.focus.specialId];
    NSLog(@"%@", str1);
    [NetHandleData getDataWithUrl:str1 completion:^(NSData *data) {
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
//        self.number = [result objectForKey:@"contentType"];
//        NSLog(@"%@", self.number);
        NSArray *tempArr = [result objectForKey:@"list"];
        
        if ([self.number isEqualToNumber:[NSNumber numberWithInt:1]]) {
//            NSLog(@"1111111111111%@", self.number);
            self.typeOneArr = [NSMutableArray array];
            
            for (NSDictionary *dic in tempArr) {
                
                TwoType *typeDetail = [[TwoType alloc] initWithDictionary:dic];
                
                [self.typeOneArr addObject:typeDetail];
                
                [typeDetail release];
            }
            
        } else if ([self.number isEqualToNumber:[NSNumber numberWithInt:2]]) {
//            NSLog(@"222222222%@", self.number);
            self.typeTwoArr = [NSMutableArray array];
            
            for (NSDictionary *dic in tempArr) {
                
                FocusFetail *foDetail = [[FocusFetail alloc] initWithDictionary:dic];
                
                [self.typeTwoArr addObject:foDetail];
                
                [foDetail release];
            }
        }
        
        [self.tableView reloadData];
    }];
    
}
- (void)viewWillAppear:(BOOL)animated
{
    
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 49, self.view.bounds.size.width, 49)];
    self.backView.tag = 30;
    [self.view addSubview:self.backView];
    self.backView.backgroundColor = [UIColor tabBarColor];
    // 返回键
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.backView addSubview:backButton];
    backButton.frame = CGRectMake(10, 10, 30, 29);
    [backButton setImage:[UIImage imageNamed:@"iconfont-gerenfanhui.png"] forState:UIControlStateNormal];
    [backButton setTintColor:[UIColor sectionColor]];
    [backButton addTarget:self action:@selector(backButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    // 播放键
    self.roundView = [JingRoundView defaultJingRoundView];
    self.roundView.frame = CGRectMake((self.view.bounds.size.width / 2) - 30, - 10, 60, 60);
    self.roundView.delegate = self;
    self.roundView.rotationDuration = 4.0;
    [_backView addSubview:self.roundView];
    [_backView release];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // 调用数据
    [self handleData];
    self.navigationItem.hidesBackButton = YES;
    self.navigationItem.title = self.focus.title;
    self.tabBarController.tabBar.hidden = YES;
    // 创建tableView
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    // 给一张背景照片
    UIImageView *back = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"tableViewback.jpg"]];
    self.tableView.backgroundView = back;
    [back release];

    [_tableView release];
    
}
// 自定义tabbar中播放按钮方法
-(void)playStatuUpdate:(BOOL)playState
{
    NSLog(@"%@...", playState ? @"播放": @"暂停了");
    if (playState == YES) {
        NSLog(@"播放");
        AvReadioPlayer *avPlayer = [AvReadioPlayer defaultAvPlayer];
        [avPlayer play];
    } else {
        NSLog(@"暂停");
        AvReadioPlayer *avPlayer = [AvReadioPlayer defaultAvPlayer];
        [avPlayer pause];
        
    }
}
- (void)backButtonClicked:(UIButton *)button
{
    NSLog(@"返回上一页");
    [self.navigationController popViewControllerAnimated:YES];
}
// section 个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if ([self.number isEqualToNumber:[NSNumber numberWithInt:1]]) {
        return self.typeOneArr.count;
    } else if ([self.number isEqualToNumber:[NSNumber numberWithInt:2]]) {
        return self.typeTwoArr.count;
    } else {
        return 0;
    }
}
// section 高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
// 自定义 section
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *sectionView = [[UIView alloc] init];
    sectionView.backgroundColor = [UIColor clearColor];
    return sectionView;
}
// cell 个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
// cell 高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 根据内容计算高度
    NSString *title = [[self.typeTwoArr objectAtIndex:indexPath.section] title];
    NSDictionary *dic = @{NSFontAttributeName:[UIFont systemFontOfSize:17]};
    CGRect rect = [title boundingRectWithSize:CGSizeMake(self.tableView.bounds.size.width / 2, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    CGFloat height = rect.size.height > (kCellWidth / 6) ? rect.size.height : (kCellWidth / 6);
    return height + 55;
}
// 向cell 中放内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.number isEqualToNumber:[NSNumber numberWithInt:1]]) {
        
        static NSString *str1 = @"reuseOne";
        FocusThreeAlbumCell *cell = [tableView dequeueReusableCellWithIdentifier:str1];
        if (cell == nil) {
            cell = [[FocusThreeAlbumCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str1];
        }
        cell.twoTy = [self.typeOneArr objectAtIndex:indexPath.section];
        return cell;
    } else if ([self.number isEqualToNumber:[NSNumber numberWithInt:2]]) {
        
        static NSString *str = @"reuseTwo";
        FoThreeCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
        if (cell == nil) {
            cell = [[FoThreeCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str];
        }
        cell.fFetail = [self.typeTwoArr objectAtIndex:indexPath.section];
        return cell;
    } else {
        return nil;
    }
}
// footer 高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if ([self.number isEqualToNumber:[NSNumber numberWithInt:1]]) {
        return 0.001;
    } else {
        return 30;
    }
}
// 自定义footer
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if ([self.number isEqualToNumber:[NSNumber numberWithInt:2]]) {
        
        UIView *threeButtonView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30)] autorelease];
        // "赞"
        self.favourButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, threeButtonView.frame.size.width / 3, threeButtonView.frame.size.height)];
        self.click = NO;
        [threeButtonView addSubview:self.favourButton];
        [self.favourButton setTitle:@"赞" forState:UIControlStateNormal];
        self.favourButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [self.favourButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        self.favourButton.backgroundColor = [UIColor buttonBackColor];
        [self.favourButton addTarget:self action:@selector(favourButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_favourButton release];
        
        // "分享"
        self.talkButton = [[UIButton alloc] initWithFrame:CGRectMake(1 + threeButtonView.frame.size.width / 3, 0, threeButtonView.frame.size.width / 3, threeButtonView.frame.size.height)];
        self.talkButton.tag = section + 1000;
        [threeButtonView addSubview:self.talkButton];
        [self.talkButton setTitle:@"分享" forState:UIControlStateNormal];
        self.talkButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [self.talkButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        self.talkButton.backgroundColor = [UIColor buttonBackColor];
        [self.talkButton addTarget:self action:@selector(talkButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_talkButton release];
        
        
        // "下载"
        self.downLoadButton = [[UIButton alloc] initWithFrame:CGRectMake(2 + threeButtonView.frame.size.width / 3 * 2, 0, threeButtonView.frame.size.width / 3, threeButtonView.frame.size.height)];
        [threeButtonView addSubview:self.downLoadButton];
        self.downLoadButton.tag = section;
        [self.downLoadButton setTitle:@"下载" forState:UIControlStateNormal];
        self.downLoadButton.titleLabel.font = [UIFont systemFontOfSize:15];
        [self.downLoadButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        self.downLoadButton.backgroundColor = [UIColor buttonBackColor];
        [self.downLoadButton addTarget:self action:@selector(downLoadButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [_downLoadButton release];
        return threeButtonView;
    } else if ([self.number isEqualToNumber:[NSNumber numberWithInt:1]]) {
        UIView *hidView = [[UIView alloc] init];
        return hidView;
    } else {
        return nil;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([self.number isEqualToNumber:[NSNumber numberWithInt:1]]) {
        // 推出到专辑界面
        AlbumViewController *albumVC = [[AlbumViewController alloc] init];
        [self.navigationController pushViewController:albumVC animated:YES];
        // 给专辑界面传值
        TwoType *twoTy = [self.typeOneArr objectAtIndex:indexPath.section];
        
        ClassifyDetail *det = [[ClassifyDetail alloc] init];
        det.pageId = twoTy.myId;
        
        albumVC.classifyDetail = det;
        [det release];
    } else if ([self.number isEqualToNumber:[NSNumber numberWithInt:2]]) {
        // 推出到播放界面
        PlayViewController *playVC = [PlayViewController defaultPlayVC];
        // 给播放界面传值
        FocusFetail *twoTyp = [self.typeTwoArr objectAtIndex:indexPath.section];
        if (playVC.albumArr.count != 0) {
            [playVC.albumArr removeAllObjects];
        }
        if (playVC.hotPlayArr.count != 0) {
            [playVC.hotPlayArr removeAllObjects];
        }
        playVC.focusFetailArr = self.typeTwoArr;
        playVC.index = indexPath.section;
        playVC.focusFetail = twoTyp;
        
        [self presentViewController:playVC animated:YES completion:^{
            
        }];
//        [album release];
    }
}
- (void)favourButtonClicked:(UIButton *)button
{
    if (self.click == NO) {
        [button setTitle:@"已赞" forState:UIControlStateNormal];
        NSLog(@"已赞");
    } else {
        [button setTitle:@"赞" forState:UIControlStateNormal];
        NSLog(@"赞");
    }
    self.click = !self.click;
}
- (void)talkButtonClicked:(UIButton *)button
{
    NSLog(@"分享");
    AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    authRequest.redirectURI = REDIRECTURI;
    authRequest.scope = @"all";
    
    WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare:button.tag] authInfo:authRequest access_token:myDelegate.wbtoken];
    request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    //    request.shouldOpenWeiboAppInstallPageIfNotInstalled = NO;
    [WeiboSDK sendRequest:request];
}
- (WBMessageObject *)messageToShare:(NSInteger)tag
{
    FocusFetail *fetaill = [self.typeTwoArr objectAtIndex:tag - 1000];
    WBMessageObject *message = [WBMessageObject message];
    NSString *str = [NSString stringWithFormat:@"我使用悦享听分享了一条信息:\n%@\n%@", fetaill.title, fetaill.playPath64];
    message.text = str;
    WBImageObject *image = [WBImageObject object];
    image.imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:fetaill.coverSmall]];
    message.imageObject = image;
    return message;
}

- (void)downLoadButtonClicked:(UIButton *)button
{
    FocusFetail *hot = [self.typeTwoArr objectAtIndex:button.tag];

    NSString *fileName = [hot.title stringByAppendingFormat:@".mp3"];
    [[FilesDownManage sharedFilesDownManage]downFileUrl:hot.playPath64 filename:fileName filetarget:@"mp3" fileimage:nil];
    
    NSLog(@"下载");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
